import os
from pathlib import Path
import textwrap

def create_project_structure(base_dir):
    # 创建项目目录结构
    dirs = [
        "app/src/main/java/com/example/voicealarm",
        "app/src/main/res/layout",
        "app/src/main/res/drawable",
        "app/src/main/res/mipmap-anydpi-v26",
        "app/src/main/res/mipmap-hdpi",
        "app/src/main/res/mipmap-mdpi",
        "app/src/main/res/mipmap-xhdpi",
        "app/src/main/res/mipmap-xxhdpi",
        "app/src/main/res/mipmap-xxxhdpi",
        "app/src/main/res/values",
        "app/src/main/res/values-night",
    ]
    
    for d in dirs:
        os.makedirs(os.path.join(base_dir, d), exist_ok=True)

def create_files(base_dir):
    # 创建Java/Kotlin文件
    java_files = {
        "MainActivity.java": """
package com.example.voicealarm;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private ListView alarmListView;
    private FloatingActionButton fabAdd;
    private AlarmAdapter adapter;
    private ArrayList<Alarm> alarms = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        alarmListView = findViewById(R.id.alarm_list);
        fabAdd = findViewById(R.id.fab_add);
        
        loadAlarms();
        setupListView();
        setupAddButton();
    }

    private void loadAlarms() {
        // 示例数据
        Alarm alarm1 = new Alarm();
        alarm1.id = 1;
        alarm1.time = Calendar.getInstance();
        alarm1.time.set(Calendar.HOUR_OF_DAY, 8);
        alarm1.time.set(Calendar.MINUTE, 0);
        alarm1.activeDays = new boolean[]{false, true, true, true, true, true, false};
        alarm1.ttsText = "早上好，该起床了";
        
        Alarm alarm2 = new Alarm();
        alarm2.id = 2;
        alarm2.time = Calendar.getInstance();
        alarm2.time.set(Calendar.HOUR_OF_DAY, 22);
        alarm2.time.set(Calendar.MINUTE, 30);
        alarm2.activeDays = new boolean[]{true, true, true, true, true, true, true};
        alarm2.ttsText = "该睡觉了，晚安";
        
        alarms.add(alarm1);
        alarms.add(alarm2);
        
        Collections.sort(alarms, (a1, a2) -> a1.time.compareTo(a2.time));
    }

    private void setupListView() {
        adapter = new AlarmAdapter(this, alarms);
        alarmListView.setAdapter(adapter);
    }

    private void setupAddButton() {
        fabAdd.setOnClickListener(view -> {
            Alarm newAlarm = new Alarm();
            newAlarm.time = Calendar.getInstance();
            newAlarm.ttsText = "该起床了";
            alarms.add(newAlarm);
            adapter.notifyDataSetChanged();
        });
    }
    
    private class AlarmAdapter extends ArrayAdapter<Alarm> {
        public AlarmAdapter(MainActivity context, ArrayList<Alarm> alarms) {
            super(context, 0, alarms);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Alarm alarm = getItem(position);
            
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.alarm_item, parent, false);
            }
            
            TextView tvTime = convertView.findViewById(R.id.tv_time);
            TextView tvDays = convertView.findViewById(R.id.tv_days);
            TextView tvTts = convertView.findViewById(R.id.tv_tts);
            
            if (alarm != null) {
                tvTime.setText(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(alarm.time.getTime()));
                
                String[] days = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < alarm.activeDays.length; i++) {
                    if (alarm.activeDays[i]) {
                        if (sb.length() > 0) sb.append(",");
                        sb.append(days[i]);
                    }
                }
                tvDays.setText(sb.toString());
                tvTts.setText(alarm.ttsText);
            }
            
            return convertView;
        }
    }
}
""",

        "Alarm.java": """
package com.example.voicealarm;

import android.os.Parcel;
import android.os.Parcelable;
import java.util.Calendar;

public class Alarm implements Parcelable {
    public long id;
    public Calendar time;
    public boolean[] activeDays = new boolean[7];
    public String ttsText;

    public Alarm() {}

    protected Alarm(Parcel in) {
        id = in.readLong();
        time = (Calendar) in.readSerializable();
        activeDays = in.createBooleanArray();
        ttsText = in.readString();
    }

    public static final Creator<Alarm> CREATOR = new Creator<Alarm>() {
        @Override
        public Alarm createFromParcel(Parcel in) {
            return new Alarm(in);
        }

        @Override
        public Alarm[] newArray(int size) {
            return new Alarm[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(id);
        dest.writeSerializable(time);
        dest.writeBooleanArray(activeDays);
        dest.writeString(ttsText);
    }
}
""",

        "AlarmService.java": """
package com.example.voicealarm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import java.util.Calendar;

public class AlarmService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && "SCHEDULE_ALARM".equals(intent.getAction())) {
            Alarm alarm = intent.getParcelableExtra("alarm");
            scheduleAlarm(alarm);
        }
        return START_STICKY;
    }

    private void scheduleAlarm(Alarm alarm) {
        Calendar calendar = Calendar.getInstance();
        Calendar now = Calendar.getInstance();
        
        calendar.set(Calendar.HOUR_OF_DAY, alarm.time.get(Calendar.HOUR_OF_DAY));
        calendar.set(Calendar.MINUTE, alarm.time.get(Calendar.MINUTE));
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        
        if (calendar.before(now)) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        Intent intent = new Intent(this, AlarmReceiver.class);
        intent.putExtra("alarm", alarm);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this, (int) alarm.id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(
                    AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        } else {
            alarmManager.setExact(
                    AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }
    }
}
""",

        "AlarmReceiver.java": """
package com.example.voicealarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Alarm alarm = intent.getParcelableExtra("alarm");
        
        Intent ringIntent = new Intent(context, RingActivity.class);
        ringIntent.putExtra("alarm", alarm);
        ringIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(ringIntent);
    }
}
""",

        "RingActivity.java": """
package com.example.voicealarm;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Locale;

public class RingActivity extends AppCompatActivity {
    private TextToSpeech tts;
    private int snoozeCount = 0;
    private Alarm alarm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ring);
        
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        hideSystemUI();
        
        alarm = getIntent().getParcelableExtra("alarm");
        snoozeCount = getIntent().getIntExtra("snooze_count", 0);
        
        setupViews();
        playTts();
        setupAutoSnooze();
    }

    private void hideSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }

    private void setupViews() {
        TextView tvTts = findViewById(R.id.tv_tts);
        tvTts.setText(alarm.ttsText);
        
        Button btnDismiss = findViewById(R.id.btn_dismiss);
        Button btnSnooze = findViewById(R.id.btn_snooze);
        
        btnDismiss.setOnClickListener(v -> dismiss());
        btnSnooze.setOnClickListener(v -> snooze());
    }

    private void playTts() {
        tts = new TextToSpeech(this, status -> {
            if (status == TextToSpeech.SUCCESS) {
                tts.setLanguage(Locale.CHINESE);
                tts.speak(alarm.ttsText, TextToSpeech.QUEUE_FLUSH, null, null);
            }
        });
    }

    private void setupAutoSnooze() {
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (!isFinishing()) {
                snooze();
            }
        }, 15000);
    }

    private void dismiss() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        finish();
    }

    private void snooze() {
        snoozeCount++;
        
        if (snoozeCount >= 3) {
            dismiss();
            return;
        }
        
        if (tts != null) {
            tts.stop();
        }
        
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(this, RingActivity.class);
        intent.putExtra("alarm", alarm);
        intent.putExtra("snooze_count", snoozeCount);
        
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, (int) alarm.id * 10 + snoozeCount, 
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 10);
        
        alarmManager.setExactAndAllowWhileIdle(
                AlarmManager.RTC_WAKEUP, 
                calendar.getTimeInMillis(), 
                pendingIntent);
        
        finish();
    }

    @Override
    protected void onDestroy() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }
}
"""
    }

    # 创建布局文件
    layout_files = {
        "activity_main.xml": """
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/alarm_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:dividerHeight="1dp"
        android:padding="8dp"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_margin="16dp"
        app:srcCompat="@drawable/ic_add"/>

</RelativeLayout>
""",

        "alarm_item.xml": """
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_vertical">
        
        <TextView
            android:id="@+id/tv_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:textStyle="bold"/>
            
        <TextView
            android:id="@+id/tv_days"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginStart="16dp"
            android:textSize="14sp"/>
    </LinearLayout>

    <TextView
            android:id="@+id/tv_tts"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="16sp"
            android:ellipsize="end"
            android:maxLines="1"
            android:paddingTop="8dp"/>

</LinearLayout>
""",

        "activity_ring.xml": """
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:background="#212121"
    android:padding="24dp">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:textColor="#FFFFFF"
        android:text="闹钟提醒"/>

    <TextView
        android:id="@+id/tv_tts"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="#FFFFFF"
        android:layout_marginTop="24dp"
        android:ellipsize="end"
        android:maxLines="3"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="32dp"
        android:gravity="center">

        <Button
            android:id="@+id/btn_snooze"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginEnd="8dp"
            android:text="小睡"
            android:backgroundTint="#FF4081"/>

        <Button
            android:id="@+id/btn_dismiss"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginStart="8dp"
            android:text="关闭"
            android:backgroundTint="#4CAF50"/>
    </LinearLayout>
</LinearLayout>
"""
    }

    # 创建资源文件
    resource_files = {
        "strings.xml": """
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">语音闹钟</string>
    <string name="alarm_title">闹钟提醒</string>
    <string name="snooze">小睡</string>
    <string name="dismiss">关闭</string>
</resources>
""",

        "colors.xml": """
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
    <color name="snooze_color">#FF4081</color>
    <color name="dismiss_color">#4CAF50</color>
</resources>
""",

        "styles.xml": """
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryDark">@color/purple_700</item>
        <item name="colorAccent">@color/teal_200</item>
    </style>

    <style name="FullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowActionBar">false</item>
        <item name="android:windowBackground">@color/black</item>
    </style>
</resources>
""",

        "ic_add.xml": """
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path
        android:fillColor="#FF000000"
        android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>
""",

        "ic_launcher.xml": """
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
    <background android:drawable="@color/purple_500"/>
    <foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>
""",

        "ic_launcher_foreground.xml": """
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:aapt="http://schemas.android.com/aapt"
    android:width="108dp"
    android:height="108dp"
    android:viewportWidth="108"
    android:viewportHeight="108">
    <path
        android:fillType="evenOdd"
        android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70,46 70,46L64,56L62,66L56,72L32,64Z"
        android:strokeWidth="1"
        android:strokeColor="#00000000">
        <aapt:attr name="android:fillColor">
            <gradient
                android:endX="44.0"
                android:endY="50.0"
                android:startX="44.0"
                android:startY="0.0"
                android:type="linear">
                <item android:color="#FFFFFFFF" android:offset="0.0"/>
                <item android:color="#FFFFFFFF" android:offset="1.0"/>
            </gradient>
        </aapt:attr>
    </path>
</vector>
"""
    }

    # 创建mipmap资源
    mipmap_files = {
        "hdpi/ic_launcher.png": "",
        "mdpi/ic_launcher.png": "",
        "xhdpi/ic_launcher.png": "",
        "xxhdpi/ic_launcher.png": "",
        "xxxhdpi/ic_launcher.png": "",
        "hdpi/ic_launcher_round.png": "",
        "mdpi/ic_launcher_round.png": "",
        "xhdpi/ic_launcher_round.png": "",
        "xxhdpi/ic_launcher_round.png": "",
        "xxxhdpi/ic_launcher_round.png": "",
    }

    # 创建AndroidManifest.xml
    manifest_file = """
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.voicealarm">

    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".RingActivity"
            android:showOnLockScreen="true"
            android:turnScreenOn="true"
            android:excludeFromRecents="true"
            android:theme="@style/FullScreenTheme">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
            </intent-filter>
        </activity>

        <service android:name=".AlarmService" />

        <receiver android:name=".AlarmReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>
        </receiver>
    </application>
</manifest>
"""

    # 创建build.gradle (Module: app)
    build_gradle = """
apply plugin: 'com.android.application'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.voicealarm"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
"""

    # 创建所有文件
    for filename, content in java_files.items():
        with open(os.path.join(base_dir, f"app/src/main/java/com/example/voicealarm/{filename}"), "w", encoding="utf-8") as f:
            f.write(textwrap.dedent(content).strip())

    for filename, content in layout_files.items():
        with open(os.path.join(base_dir, f"app/src/main/res/layout/{filename}"), "w", encoding="utf-8") as f:
            f.write(textwrap.dedent(content).strip())

    for filename, content in resource_files.items():
        res_dir = "values" if filename.endswith(".xml") and filename not in ["ic_add.xml", "ic_launcher.xml", "ic_launcher_foreground.xml"] else "drawable"
        if filename == "ic_launcher.xml":
            res_dir = "mipmap-anydpi-v26"
        elif filename == "ic_launcher_foreground.xml":
            res_dir = "drawable"
        with open(os.path.join(base_dir, f"app/src/main/res/{res_dir}/{filename}"), "w", encoding="utf-8") as f:
            f.write(textwrap.dedent(content).strip())

    for filename in mipmap_files:
        # 创建空文件作为占位符，实际项目中应该放入真实的图标文件
        Path(os.path.join(base_dir, f"app/src/main/res/mipmap-{filename}")).touch()

    with open(os.path.join(base_dir, "app/src/main/AndroidManifest.xml"), "w", encoding="utf-8") as f:
        f.write(textwrap.dedent(manifest_file).strip())

    with open(os.path.join(base_dir, "app/build.gradle"), "w", encoding="utf-8") as f:
        f.write(textwrap.dedent(build_gradle).strip())

def main():
    project_name = "VoiceAlarm"
    base_dir = os.path.join(os.getcwd(), project_name)
    
    print(f"Creating Android project at: {base_dir}")
    create_project_structure(base_dir)
    create_files(base_dir)
    
    print("Project created successfully!")
    print(f"Open Android Studio and import the project from: {base_dir}")

if __name__ == "__main__":
    main()
